package com.yfree.global

import com.yfree.config.YConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.json.GsonHttpMessageConverter
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

@Configuration
class YGlobalConfiguration {
    @Bean
    fun configurer(): WebMvcConfigurer {
        return object : WebMvcConfigurer {
            @Autowired
            lateinit var yFilter: YFilter

            override fun addInterceptors(registry: InterceptorRegistry) {
                registry.addInterceptor(yFilter).addPathPatterns("/**")
            }

            override fun addCorsMappings(registry: CorsRegistry) {
                registry.addMapping("/*")
                        .allowedOrigins(*YConfig.Request.allowedOrigins)
                        .allowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS)
                        .allowedMethods(HttpMethod.GET.name, HttpMethod.POST.name)
                        .maxAge(CrossOrigin.DEFAULT_MAX_AGE)
            }

            override fun extendMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
                converters.removeIf { it is MappingJackson2HttpMessageConverter }
                converters.add(GsonHttpMessageConverter())
                super.extendMessageConverters(converters)
            }
        }
    }
}
